package com.yumeng.webapp.shiro.config;

import com.yumeng.framework.auth.bean.AuthExtDataInfo;
import com.yumeng.framework.auth.service.AuthExtDataHandler;
import com.yumeng.framework.auth.shiro.config.ShiroConfiguration;
import com.yumeng.framework.auth.shiro.helper.PasswordHelper;
import com.yumeng.framework.auth.shiro.realm.UsernameRealm;
import com.yumeng.system.main.auth.NormalAuthServiceImpl;
import jakarta.servlet.Filter;
import org.apache.shiro.realm.Realm;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author wxd
 * @date 2025/9/28 20:00
 */
//@Configuration
public class ShiroConfig extends ShiroConfiguration {

    /**
     * 创建Realm
     */
    @Bean(name=UsernameRealm.DEFAULT_BEAN_NAME)
    public UsernameRealm getRealm(){
        UsernameRealm realm = new UsernameRealm(NormalAuthServiceImpl.DEFAULT_BEAN_NAME);
        realm.setCredentialsMatcher(PasswordHelper.createHashedCredentialsMatcher());
        return realm;
    }

    /** 自定义过滤器 */
    @Override
    protected LinkedHashMap<String, Filter> getFilterMap() {
        return null;
/*        LinkedHashMap<String, Filter> map = new LinkedHashMap<>();
        LogoutFilter logout = new LogoutFilter();
        logout.setPostOnlyLogout(true);
        logout.setRedirectUrl("/shiro/toLogin.vw");//注销后跳转至登录页面
        map.put("logout", logout);

        return map;*/
    }

    @Override
    protected LinkedHashMap<String, String> getFilterChainDefinitionMap() {
        LinkedHashMap<String,String> filterMap = new LinkedHashMap<String,String>();
        filterMap.put("/test/**", "anon");
        //druid数据库连接池信息
        filterMap.put("/druid/**","authc, roles[admin]");

        filterMap.put("/shiro/testUserLevelPage.vw", "user");

        //授权过滤器
        //注意：当前授权拦截后，shiro会自动跳转到未授权页面
        //perms括号中的内容是权限的值
        filterMap.put("/perm/toAddDemoUser.vw", "perms[demo:user:add,root]");//demo:user:add 和 root 权限都拥有才可以访问
        filterMap.put("/perm/toUpdateDemoUser.vw", "perms[demo:user:update]");
        return filterMap;
    }

    /** 获取所有Realms */
    @Override
    public Collection<Realm> getRealms() {
        Collection<Realm> realms = new ArrayList<Realm>(1);
        realms.add(getRealm());
        return realms;
    }

    /**
     * 自定义认证扩展信息
     *
     * @return
     */
    @Bean
    public AuthExtDataHandler authExtDataHandler(){
        return authInfo -> {
            AuthExtDataInfo dataInfo = new AuthExtDataInfo();
            Map<String, Object> dataMap = Map.of("entId", 22222, "userName", "ddz");
            Map<String, Object> loginInfo = Map.of("authEntId", "33333", "authUserName", "4444444444");
            dataInfo.setDataMap(dataMap);
            dataInfo.setLoginInfo(loginInfo);
            return dataInfo;
        };
    }

}
